<?php

namespace addons\vote\controllers;
use addons\member\models\Member;
use addons\vote\models\VoteLogModel;
use controllers\AdminApi;

class index extends AdminApi {
    /**
     * 初始化
     */
    public function onStepUp(){
        $this->model = new VoteLogModel();
    }

    /**
     * 分类接口
     * @param string $title
     * @return array
     */
    public function index($title = '') {
        $map = [];
        $time = $this->getRequestTime();
        $uid = self::$get['uid'];
        $touid = self::$get['touid'];
        if ($time){
			$time = array_map(function ($item){
				return strtotime($item);
			} , $time);
        	$map['a.create_time'] = ['between' , $time];
		}
        if ($uid){
			if (is_numeric($uid)){
				$map['a.uid'] = $uid;
			}else{
				$map['m.name'] = $uid;
			}
		}
		if ($touid){
			if (is_numeric($touid)){
				$map['a.touid'] = $touid;
			}else{
				$map['t.name'] = $touid;
			}
		}

        $data = $this->model->where($map)->alias('a')->join('@member as m' , 'm.id = a.uid')->join('@member as t' , 't.id = a.touid')->field('a.*,m.name,t.name as toname')->select();
        foreach ($data as &$val){
        	$val['create_time'] = timeFormat($val['create_time']);
		}
        return self::returnJson($data);
    }

	/**
	 * 部门
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-13 下午9:40
	 */
    public function deparent(){
    	$id = self::$get['id'];
    	$selected = 0;
    	if ($id > 0){
    		$useModel = new Member();
    		$find = $useModel->where(['id' => $id])->find();
    		if ($find){
    			$selected = $find['deparent_id'];
			}
		}
    	$model = new VoteLogModel();
    	return success($this->getSelectOptions($model->deparents , $selected));
	}

	protected function onFind(){
        return $this->getFind();
    }

	/**
	 * 更新前操作
	 * @param array $data
	 * @return bool
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-08 下午10:05
	 */
    public function onUpdateBefore(&$data = []) {
    	if (!$this->model->ticketValid($data['uid'] , $data['touid'])){
    		$this->error = $this->model->error;
    		return false;
		}
		return parent::onUpdateBefore($data); // TODO: Change the autogenerated stub
	}

	/**
	 * 更新后操作
	 * @param bool|int $status
	 * @param array $data
	 * @param array $find
	 * @return bool
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-08 下午10:05
	 */
	public function onUpdateAfter($status , &$data = [] , $find = []) {
    	// 更新票数
		$ticket = 1;
		$this->model->updateUserTicket($data['touid'] , $data['uid'] , $ticket);
		return parent::onUpdateAfter($status , $data , $find); // TODO: Change the autogenerated stub
	}

	/**
	 * 设置弹窗标题
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setPageTitle() {
		return '投票';
	}

	/**
	 * 设置面包屑
	 * @return array
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setCrumbs() {
		return ['投票管理' , '投票记录'];
	}
}
